package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.config.ConstantPropertiesUtil;
import com.atguigu.yygh.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        try {
            String endpoint = ConstantPropertiesUtil.END_POINT;
            String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
            String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();

            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            filename=uuid+filename;

            //文件分类 优化
                //2001/09/01/abc.jpg
            String dateUrl = new DateTime().toString("yyyy/MM/dd");
            filename =dateUrl +"/"+filename;

            //文件上传阿里云
            ossClient.putObject(bucketName,filename,inputStream);

            String url ="https://" +bucketName +"."+endpoint+"/"+filename;
            return url;


        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }
}